<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      :title="!dataForm.id ? $t('add') : $t('update')"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="60%"
      top="90px"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmitHandle2()"
        :label-width="$i18n.locale === 'en-US' ? '100px' : '100px'"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="dataForm.title"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="经纬度" prop="lonandLat">
              <el-input
                v-model="dataForm.lonandLat"
                style="width: 60%; margin-right: 10px"
              ></el-input>
              <el-button type="primary" size="mini" @click="mapCli()"
                >地图选点</el-button
              >
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input v-model="dataForm.longitude"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="latitude">
                        <el-input v-model="dataForm.latitude"></el-input>
                    </el-form-item>
                </el-col> -->
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="dataForm.type">
                <el-radio :label="2">住宿 </el-radio>
                <el-radio :label="1">美食 </el-radio>
                <el-radio :label="0">景点</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <el-input
                v-model="dataForm.content"
                placeholder="内容"
                type="textarea"
                :rows="2"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <p class="pdl60">
              攻略详情图<span>(支持png、jpg，建议尺寸750*980px，最多10张)</span>
            </p>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="pic">
              <el-upload
                :action="url"
                :file-list="fileList"
                :limit="10"
                :before-upload="beforeUploadHandle"
                list-type="picture-card"
                :on-success="successHandle"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <editor-vue
                style="margin-top: -30px"
                :content="dataForm.content"
                @EditorChange="getEditor"
                ref="infoIntroduceRef"
              ></editor-vue>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <mapdiv style="width:96%;margin:0 auto 20px"></mapdiv> -->
      </el-form>
      <template slot="footer">
        <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{
          $t("confirm")
        }}</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="mapShow" title="地图选点" top="70px">
      <mapdiv
        ref="mapDiv"
        style="width: 96%; margin: 0 auto 20px"
        :longitude="dataForm.longitude"
        :latitude="dataForm.latitude"
        @getPos="getPosVal($event)"
      >
      </mapdiv>
    </el-dialog>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import mapdiv from "../data/map-data/map2";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
export default {
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      fileList: [],
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      mapShow: false,
      visible: false,
      dialogImageUrl: "",
      dialogVisible: false,
      dataForm: {
        content: "",
        id: "",
        title: "",
        type: "",
        publisherType: 5,
        lonandLat: "",
        latitude: "",
        longitude: "",
        pic: [],
      },
    };
  },
  components: {
    mapdiv,
    editorVue,
  },
  computed: {
    dataRule() {
      return {
        type: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        pic: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        // latitude: [
        //   {
        //     required: true,
        //     message: this.$t("validate.required"),
        //     trigger: "blur",
        //   },
        // ],
        // pic: [{
        //     required: true,
        //     message: this.$t("validate.required"),
        //     trigger: "blur",
        // }, ],
      };
    },
  },
  props: ["publisherType"],
  methods: {
    getEditor(val) {
      this.dataForm.content = val;
    },
    mapCli() {
      this.mapShow = true;
      this.$nextTick(() => {
        this.$refs.mapDiv.initMap();
      });
    },
    getPosVal(obj) {
      this.mapShow = false;
      this.dataForm.latitude = obj.lat;
      this.dataForm.longitude = obj.lon;
      this.dataForm.lonandLat = obj.lon + "," + obj.lat;
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.fileList = [];
        this.$refs["dataForm"].resetFields();
        this.dataForm.publisherType = this.publisherType;
        if (this.dataForm.id) {
          this.getInfo();
        } else {
          this.$nextTick(() => {
            this.$refs.infoIntroduceRef.init();
          });
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/scenic/tripintrodution/details?id=" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          let picArr = this.dataForm.pic.split(",");
          for (let i = 0; i < picArr.length; i++) {
            this.fileList.push({
              url: picArr[i],
            });
          }
          this.$nextTick(() => {
            this.$refs.infoIntroduceRef.init();
          });
        })
        .catch(() => {});
    },
    handleRemove(file, fileList) {
      this.fileList = fileList.map((item) => {
        return item;
      });
    },
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },

    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.successHandle(res.data);
          }
        });
      }
    },
    // 上传成功
    successHandle(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.fileList.push({
        name: "",
        url: res.data.url,
      });
    },
    dataFormSubmitHandle: debounce(
      function () {
        let picArr = [];
        this.fileList.filter((item) => {
          picArr.push(item.url);
        });
        this.dataForm.pic = picArr.join(",");
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let url = "";
          if (!this.dataForm.id) {
            url = "/scenic/tripintrodution/add";
          } else {
            url = "/scenic/tripintrodution/update";
          }
          this.$http[!this.dataForm.id ? "post" : "put"](url, this.dataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style scoped>
.txt {
  line-height: 40px;
  height: 40px;
  margin: 0;
  padding: 0;
}
</style>
